package com.example.zkweixiu.app.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.example.zkweixiu.app.R;
import com.example.zkweixiu.app.bean.BigUserBean;
import com.example.zkweixiu.app.bean.CitBean;
import com.example.zkweixiu.app.bean.ConnBean;
import com.example.zkweixiu.app.bean.JsonBean;
import com.example.zkweixiu.app.bean.LikeUserBean;
import com.example.zkweixiu.app.bean.ObjBean;
import com.example.zkweixiu.app.bean.ProBean;
import com.example.zkweixiu.app.bean.UnitUDBean;
import com.example.zkweixiu.app.bean.UserBean;
import com.example.zkweixiu.app.pro.PublicPro;
import com.example.zkweixiu.app.utils.SPUtils;
import com.google.gson.Gson;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.RxLocationTool;
import com.vondear.rxtool.model.ActionItem;
import com.vondear.rxtool.model.Gps;
import com.vondear.rxui.view.popupwindows.RxPopupSingleView;
import com.yanzhenjie.sofia.Sofia;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.joda.time.DateTime;
import org.joda.time.Days;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 添加用户信息
 */
public class AddUserDataActivity extends AppCompatActivity implements View.OnClickListener, LocationListener {
    private List<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    private ProBean proBean;
    private CitBean citBean;
    private ConnBean connBean;
    private Context context;

    private String conn_uuid = "-1";
    private String cit_uuid = "-1";
    private String pro_uuid = "-1";
    private TextView tv_data6;
    private EditText tv_data5;

    private RxPopupSingleView titlePopup;

    private boolean is = true;
    private UnitUDBean unitUDBean;
    private RelativeLayout tv_data5_5;
    private EditText tv_data2;
    private LikeUserBean likeUserBean;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 200:
/*                    if (is){
                        is = false;

                    }*/
                    if (unitUDBean.getData() == null || unitUDBean.getData().size() == 0 || unitUDBean.getStatus() != 200) {

                        return;
                    }

                    initPopupView();
                    //   titlePopup.cleanAction();

                    titlePopup.show(tv_data5_5);

                    break;

                case 201:

                    if (likeUserBean.getData() == null || likeUserBean.getData().size() == 0 || likeUserBean.getStatus() != 200) {

                        return;
                    }
                    initPopupView2();
                    //   titlePopup.cleanAction();

                    titlePopup.show(tv_data2);
                    break;


                case 303:
                    initPopupView3();
                    //   titlePopup.cleanAction();

                    titlePopup.show(tv_data11);


                    break;
            }
        }
    };
    private EditText tv_data4;
    private EditText tv_data9;
    private String locations = "-1";
    private EditText tv_data8;
    private EditText tv_data3;
    private BigUserBean bigUserBean;
    private TextView tv_data11;
    private String big_user_uuid = "0";
    private RelativeLayout tv_data11_1;
    private LinearLayout ll_qued;
    private EditText tv_data10;
    private EditText tv_data7;

    private void initPopupView2() {
        titlePopup = new RxPopupSingleView(context, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.popupwindow_definition_layout2);

        titlePopup.setFocusable(false);

        for (LikeUserBean.DataBean datum : likeUserBean.getData()) {
            titlePopup.addAction(new ActionItem(datum.getAppName()));
        }


        titlePopup.setColorItemText(Color.parseColor("#000000"));
        titlePopup.setItemOnClickListener(new RxPopupSingleView.OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                // TODO Auto-generated method stub
                //  position1 = relBean.getData().get(position).getId();

                RxKeyboardTool.hideSoftInput((Activity) context);
                tv_data2.setText(titlePopup.getAction(position).mTitle);

                if (likeUserBean.getData().get(position).getAppPhone() != null) {
                    tv_data4.setText(likeUserBean.getData().get(position).getAppPhone());

                }

                if (likeUserBean.getData().get(position).getUserNumber() != null) {
                    tv_data9.setText(likeUserBean.getData().get(position).getUserNumber());

                }

            }
        });
    }


    private void initPopupView3() {
        titlePopup = new RxPopupSingleView(context, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.popupwindow_definition_layout2);

        titlePopup.setFocusable(false);

        titlePopup.addAction(new ActionItem("无"));
        for (BigUserBean.DataBean datum : bigUserBean.getData()) {
            titlePopup.addAction(new ActionItem(datum.getSetName()));
        }
/*        for (String datum : unitUDBean.getData()) {


        }*/

        titlePopup.setColorItemText(Color.parseColor("#000000"));
        titlePopup.setItemOnClickListener(new RxPopupSingleView.OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                // TODO Auto-generated method stub
                //  position1 = relBean.getData().get(position).getId();

                //    RxKeyboardTool.hideSoftInput((Activity) context);

                if (position == 0) {
                    big_user_uuid = "0";
                    tv_data11.setText(titlePopup.getAction(position).mTitle);
                } else {
                    big_user_uuid = bigUserBean.getData().get(position - 1).getUuid();
                    tv_data11.setText(titlePopup.getAction(position).mTitle);
                }


            }
        });
    }


    private void initPopupView() {
        titlePopup = new RxPopupSingleView(context, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.popupwindow_definition_layout2);

        titlePopup.setFocusable(false);

        for (String datum : unitUDBean.getData()) {
            titlePopup.addAction(new ActionItem(datum));

        }

        titlePopup.setColorItemText(Color.parseColor("#000000"));
        titlePopup.setItemOnClickListener(new RxPopupSingleView.OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                // TODO Auto-generated method stub
                //  position1 = relBean.getData().get(position).getId();
                RxKeyboardTool.hideSoftInput((Activity) context);
                tv_data5.setText(titlePopup.getAction(position).mTitle);


            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_user_data);
        context = AddUserDataActivity.this;
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        Sofia.with(AddUserDataActivity.this).statusBarDarkFont().statusBarBackground(Color.parseColor("#FFFFFF"));

        initCustomeCityData();
        initView();

        initLocation();
        gpsCheck();

    }

    private void initView() {
        ImageView iv_sao = findViewById(R.id.iv_sao);

        RelativeLayout tv_data6_6 = findViewById(R.id.tv_data6_6);
        tv_data5_5 = findViewById(R.id.tv_data5_5);
        tv_data5 = findViewById(R.id.tv_data5); //技术组id输入框
        tv_data6 = findViewById(R.id.tv_data6);
        tv_data4 = findViewById(R.id.tv_data4); //手机号
        tv_data9 = findViewById(R.id.tv_data9); //身份证号
        tv_data3 = findViewById(R.id.tv_data3); //合同编号
        tv_data10 = findViewById(R.id.tv_data10); //设备别名
        View view_fh = findViewById(R.id.view_fh); //返回

        tv_data7 = findViewById(R.id.tv_data7);  //详细地址

        //大客户
        tv_data11 = findViewById(R.id.tv_data11);

        tv_data2 = findViewById(R.id.tv_data2);//姓名输入框

        ll_qued = findViewById(R.id.ll_qued); //确定

        TextView tv_data1 = findViewById(R.id.tv_data1);//安装人员姓名

        tv_data8 = findViewById(R.id.tv_data8); //经纬
        ImageView tv_data8_1 = findViewById(R.id.tv_data8_1);//姓名输入框

        //弹出大客户列表
        tv_data11_1 = findViewById(R.id.tv_data11_1);

        tv_data4.setRawInputType(InputType.TYPE_CLASS_NUMBER); //首选输入类型为数字
        tv_data9.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        tv_data5.setRawInputType(InputType.TYPE_CLASS_NUMBER);
        tv_data3.setRawInputType(InputType.TYPE_CLASS_NUMBER);


        iv_sao.setOnClickListener(this);
        tv_data6_6.setOnClickListener(this);
        tv_data8_1.setOnClickListener(this);
        tv_data11_1.setOnClickListener(this);
        ll_qued.setOnClickListener(this);
        view_fh.setOnClickListener(this);

        tv_data5.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //    Log.e("tv_data6", "beforeTextChanged");
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //    Log.e("tv_data6", "onTextChanged");
                getLikeUnit(charSequence.toString());

            }

            @Override
            public void afterTextChanged(Editable editable) {
                //  Log.e("tv_data6", "afterTextChanged");
                // 接口调用 模糊查询
                //  tv_data5.setText(end);


            }
        });


        tv_data2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                getLikeUser(charSequence.toString());

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });


        if (PublicPro.userBean != null) {
            tv_data1.setText(PublicPro.userBean.getData().getGuaName());

  /*          library_normal_ratingbar.setRating(PublicPro.userBean.getData().getGuaLevel());

            DateTime dt1 = new DateTime(PublicPro.userBean.getData().getGuaTime()); //账号创建时间
            DateTime dt2 = new DateTime(new DateTime().getMillis()); //当前时间
            tv_tiezhu2.setText("在岗"+ Days.daysBetween(dt1, dt2).getDays() + "天 "); //计算时间差*/
        } else {
            RxActivityTool.skipActivityAndFinishAll(context, LoginActivity.class);
        }

    }

    /**
     * 模糊查询用户姓名
     */
    private void getLikeUser(String toString) {
        OkHttpUtils
                .get()
                .url(PublicPro.USER_LINKE)
                .addParams("like_name", toString)
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        likeUserBean = new Gson().fromJson(response, LikeUserBean.class);

                        if (likeUserBean.getData() == null || likeUserBean.getData().size() == 0 || likeUserBean.getStatus() != 200) {

                            return;
                        } else {
                            handler.sendEmptyMessage(201);
                        }
                    }
                });
    }

    /**
     * 模糊查询
     */
    private void getLikeUnit(String toString) {
        OkHttpUtils
                .get()
                .url(PublicPro.UNIT_LINKE)
                .addParams("link_uuid", toString)
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        unitUDBean = new Gson().fromJson(response, UnitUDBean.class);

                        if (unitUDBean.getData() == null || unitUDBean.getData().size() == 0 || unitUDBean.getStatus() != 200) {

                            return;
                        } else {
                            handler.sendEmptyMessage(200);
                        }
                    }
                });
    }


    private void initCustomeCityData() {
        String json = getJson("pro.json", context);
        String json2 = getJson("cit.json", context);
        String json3 = getJson("coun.json", context);

        proBean = new Gson().fromJson(json, ProBean.class);
        citBean = new Gson().fromJson(json2, CitBean.class);
        connBean = new Gson().fromJson(json3, ConnBean.class);

        // JsonBean
        for (ProBean.DataBean datum : proBean.getData()) {
            JsonBean jsonBean = new JsonBean();
            ArrayList<String> cityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）
            for (CitBean.DataBean citBeanDatum : citBean.getData()) { //遍历城市
                if (citBeanDatum.getProvinceId().equals(datum.getValue())) {//该城市的所有地区列表
                    cityList.add(citBeanDatum.getLabel()); //添加城市
                    ArrayList<String> city_AreaList = new ArrayList<>();//该城市的所有地区列表
                    for (ConnBean.DataBean connBeanDatum : connBean.getData()) { //遍历地区
                        if (connBeanDatum.getCityId().equals(citBeanDatum.getValue())) {
                            //该省的城市列表（第二级）
                            //  connList = new ArrayList<>();
                            city_AreaList.add(connBeanDatum.getLabel()); //添加地区
                        }
                    }

                    province_AreaList.add(city_AreaList);//添加该省所有地区数据
                    //  city_AreaList.add(connList)
                }

            }

            jsonBean.setName(datum.getLabel());
            // jsonBean.setId();
            options1Items.add(jsonBean);
            /**
             * 添加城市数据
             */
            options2Items.add(cityList);

            /**
             * 添加地区数据
             */
            options3Items.add(province_AreaList);
        }


    }


    public String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_sao:
                Intent intent = new Intent(AddUserDataActivity.this, ActivityScanerCode.class);
                startActivity(intent);
                break;

            case R.id.tv_data6_6:
                RxKeyboardTool.hideSoftInput((Activity) context);

                showPickerView();
                break;

            case R.id.tv_data8_1:
                //   RxKeyboardTool.hideSoftInput((Activity) context);
                if ("-1".equals(locations)) {
                    Toast.makeText(context, "正在获取定位...", Toast.LENGTH_SHORT).show();
                    gpsCheck();
                    return;
                }

                Toast.makeText(context, "获取成功", Toast.LENGTH_SHORT).show();
                tv_data8.setText(locations);
                break;

            case R.id.tv_data11_1:
                getBigUserList();
                break;

            case R.id.ll_qued:
                String ope_user = PublicPro.userBean.getData().getGuaName();//操作人员姓名
                String ope_uuid = PublicPro.userBean.getData().getGuaUuid();//操作人员uuid
                String set_alias = tv_data10.getText().toString().trim();//设备别名
                String set_vol_uuid = big_user_uuid;//大客户uuid
                String pact_num = tv_data3.getText().toString().trim();//合同编号
                String address = tv_data7.getText().toString().trim();//详细地址

/*                conn_uuid = "-1";
                cit_uuid = "-1";
                pro_uuid = "-1";*/
                String deat = tv_data8.getText().toString().trim();// 经纬度
                if ("-1".equals(locations) || TextUtils.isEmpty(deat)) {
                    Toast.makeText(context, "请先获取定位", Toast.LENGTH_SHORT).show();
                    //   gpsCheck();
                    return;
                }

                String[] split = deat.split(",");
                String longitude1 = split[0];
                String latitude = split[1];
                String user_number = tv_data9.getText().toString().trim(); //身份号
                String user_phone = tv_data4.getText().toString().trim(); //手机号
                String user_name = tv_data2.getText().toString().trim(); //姓名
                String unit_uuid = tv_data5.getText().toString().trim(); //机组uuid

                if (TextUtils.isEmpty(set_alias)) {
                    Toast.makeText(context, "请输入设备别名", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(pact_num)) {
                    Toast.makeText(context, "请输入合同编号", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(address)) {
                    Toast.makeText(context, "请输入详细地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(user_number)) {
                    user_number = "0";
         /*           Toast.makeText(context, "请输入身份证号", Toast.LENGTH_SHORT).show();
                    return;*/
                }

                if (TextUtils.isEmpty(user_phone)) {
                    Toast.makeText(context, "请输入用户手机号", Toast.LENGTH_SHORT).show();
                    return;
                }


                if (TextUtils.isEmpty(user_name)) {
                    Toast.makeText(context, "请输入用户姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(unit_uuid)) {
                    Toast.makeText(context, "请输入用户机组ID", Toast.LENGTH_SHORT).show();
                    return;
                }
                if ("-1".equals(conn_uuid) || "-1".equals(cit_uuid) || "-1".equals(pro_uuid)) {
                    Toast.makeText(context, "请先选择地区", Toast.LENGTH_SHORT).show();
                    return;
                }

/*                conn_uuid = "-1";
                cit_uuid = "-1";
                pro_uuid = "-1"*/

                addUserUnit(ope_user, ope_uuid, set_alias, set_vol_uuid, pact_num, address, longitude1
                        , latitude, user_number, user_phone, user_name, unit_uuid);


                break;

            case R.id.view_fh:
                finish();
                break;
        }
    }


    /**
     * 为用户添加设备
     */
    private void addUserUnit(String ope_user, String ope_uuid, String set_alias, String set_vol_uuid, String pact_num, String address, String longitude1, String latitude, String user_number, String user_phone, String user_name, String unit_uuid) {
        OkHttpUtils
                .get()
                .url(PublicPro.ADD_USER_UNIT)
                .addParams("unit_uuid", unit_uuid)
                .addParams("user_name", user_name)
                .addParams("user_phone", user_phone)
                .addParams("user_number", user_number)
                .addParams("longitude", longitude1)
                .addParams("latitude", latitude)
                .addParams("province", pro_uuid)
                .addParams("city", cit_uuid)
                .addParams("country", conn_uuid)
                .addParams("address", address)
                .addParams("pact_num", pact_num)
                .addParams("set_vol_uuid", set_vol_uuid)
                .addParams("set_alias", set_alias)
                .addParams("ope_user", set_alias)
                .addParams("ope_uuid", set_alias)
                .addParams("token", PublicPro.userBean.getData().getGuaToken())
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        ObjBean objBean = new Gson().fromJson(response, ObjBean.class);

                        if (objBean.getStatus() == 200) {
                            Toast.makeText(context, "添加成功", Toast.LENGTH_SHORT).show();
                            finish();

                            return;
                        } else {
                            Toast.makeText(context, objBean.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    /**
     * 获取大客户列表
     */
    private void getBigUserList() {
        OkHttpUtils
                .get()
                .url(PublicPro.BIG_USER_LIST)
                .build()
                .execute(new StringCallback() {


                    @Override
                    public void onError(okhttp3.Call call, Exception e, int id) {
                        Log.e("HomeFragment1", e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Log.e("HomeFragment1", response);

                        bigUserBean = new Gson().fromJson(response, BigUserBean.class);

                        if (bigUserBean.getData() == null || bigUserBean.getData().size() == 0 || bigUserBean.getStatus() != 200) {

                            return;
                        } else {
                            handler.sendEmptyMessage(303);
                        }
                    }
                });


    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {


            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String opt1tx = options1Items.size() > 0 ?
                        options1Items.get(options1).getPickerViewText() : "";

                String opt2tx = options2Items.size() > 0
                        && options2Items.get(options1).size() > 0 ?
                        options2Items.get(options1).get(options2) : "";

                String opt3tx = options2Items.size() > 0
                        && options3Items.get(options1).size() > 0
                        && options3Items.get(options1).get(options2).size() > 0 ?
                        options3Items.get(options1).get(options2).get(options3) : "";


                for (ProBean.DataBean datum : proBean.getData()) {
                    if (datum.getLabel().equals(opt1tx)) {
                        //省级id
                        pro_uuid = datum.getValue();
                    }
                }

                for (CitBean.DataBean datum : citBean.getData()) {
                    if (datum.getLabel().equals(opt2tx)) {


                        if (datum.getProvinceId().equals(pro_uuid)) {
                            //市区id

                            cit_uuid = datum.getValue();
                        }


                    }
                }

                for (ConnBean.DataBean datum : connBean.getData()) {
                    if (datum.getLabel().equals(opt3tx)) {
                        //地区id
                        if (datum.getCityId().equals(cit_uuid)) {
                            conn_uuid = datum.getValue();

                        }
                    }
                }

                String add_name = opt1tx + opt2tx + opt3tx;
                tv_data6.setText(add_name);
/*                String tx = pro_uuid + cit_uuid + conn_uuid;
                Log.e("onOptionsSelect", pro_uuid);
                Log.e("onOptionsSelect", cit_uuid);
                Log.e("onOptionsSelect", conn_uuid);
                Toast.makeText(GetAssActivity.this, tx, Toast.LENGTH_SHORT).show();*/
            }
        })
                .setCancelText("取消")
                .setSubmitText("确定")
                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object event) {
        String ens = event.toString();
        if (ens.contains("code//:")) {
            String[] split = ens.split("//:", 2);

            tv_data5.setText(split[1]);

        }
    }


    //--------------------------------------------------------获取定位---------------------------------------------------------
    private LocationManager locationManager;

    private void initLocation() {
        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

    }


    private void gpsCheck() {
        if (!RxLocationTool.isGpsEnabled(this)) {
            MaterialDialog.Builder builder = new MaterialDialog.Builder(this);
            MaterialDialog materialDialog = builder.title("GPS未打开").content("您需要在系统设置中打开GPS方可采集数据").positiveText("去设置")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            RxLocationTool.openGpsSettings(context);
                        }
                    }).build();
            materialDialog.setCanceledOnTouchOutside(false);
            materialDialog.setCancelable(false);
            materialDialog.show();
        } else {
            getLocation();
        }
    }


    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((AddUserDataActivity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 13000, 0, this);
        locationManager.addGpsStatusListener(new GpsStatus.Listener() {
            @Override
            public void onGpsStatusChanged(int event) {
                switch (event) {
                    case GpsStatus.GPS_EVENT_STARTED:
                        System.out.println("GPS_EVENT_STARTED");
                        break;
                    case GpsStatus.GPS_EVENT_FIRST_FIX:
                        System.out.println("GPS_EVENT_FIRST_FIX");
                        break;
                    case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                        System.out.println("GPS_EVENT_SATELLITE_STATUS");
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }
                        GpsStatus gpsStatus = locationManager.getGpsStatus(null);
                        Iterable<GpsSatellite> gpsSatellites = gpsStatus.getSatellites();
                        int count = 0;
                        Iterator iterator = gpsSatellites.iterator();
                        while (iterator.hasNext()) {
                            count++;
                            iterator.next();
                        }
                        //  mGpsCount.setText(count + "");
                        break;
                    case GpsStatus.GPS_EVENT_STOPPED:
                        System.out.println("GPS_EVENT_STOPPED");
                        //gpsState.setText("已停止定位");
                        break;
                }
            }
        });
    }

    @Override
    public void onLocationChanged(Location location) {
        Gps gps = RxLocationTool.GCJ02ToBD09(location.getLongitude(), location.getLatitude());

        locations = gps.getLongitude() + "," + gps.getLatitude();
        //      editText.setText(gps.getLongitude() + "," + gps.getLatitude());

        //   ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
//创建ClipData对象
//第一个参数只是一个标记，随便传入。
//第二个参数是要复制到剪贴版的内容
        //   ClipData clip = ClipData.newPlainText("simple text", gps.getLongitude() + "," + gps.getLatitude());
//传入clipdata对象.
        //  clipboard.setPrimaryClip(clip);

        //  Toast.makeText(context, "经纬度已自动复制到粘贴板", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}
